package com.yntx.usercenter.base.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yntx.usercenter.base.converter.TenantConverter;
import com.yntx.usercenter.base.dto.TenantDTO;
import com.yntx.usercenter.base.dto.TenantDeleteDTO;
import com.yntx.usercenter.base.dto.TenantUpdateDTO;
import com.yntx.usercenter.base.mapper.TenantMapper;
import com.yntx.usercenter.base.po.Tenant;
import com.yntx.usercenter.base.service.TenantService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@AllArgsConstructor
@DS("base")
public class TenantServiceImpl implements TenantService {

    private TenantMapper tenantMapper;

    private final TenantConverter CONVERT = TenantConverter.INSTANCE;

    @Override
    public Tenant getById(Long id) {
        return tenantMapper.selectById(id);
    }

    @Override
    public Long addTenant(TenantDTO dto) {
        checkData(dto);
        Tenant tenant = CONVERT.tenantDTO2Tenant(dto);
        tenant.setDatasourceUrl(String.format("jdbc:mysql://localhost:3306/user_center_%s?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false&createDatabaseIfNotExist=true",dto.getTenantId()));
        tenant.setDatasourceDriver("com.mysql.cj.jdbc.Driver");
        tenant.setDatasourceUsername("root");
        tenant.setDatasourceUsername("123456");
        tenantMapper.insert(tenant);
        return tenant.getId();
    }

    /**
     * 检查数据
     *
     * @param dto dto
     */
    private void checkData(TenantDTO dto) {
        LambdaQueryWrapper<Tenant> query = new LambdaQueryWrapper<Tenant>()
                .eq(Tenant::getTenantId, dto.getTenantId());
        boolean exists = tenantMapper.exists(query);
        if (exists) {
            throw new RuntimeException("租户已存在");
        }
    }

    @Override
    public void deleteTenant(TenantDeleteDTO dto) {
        LambdaQueryWrapper<Tenant> query;
        if (dto.getId() != null) {
            query = new LambdaQueryWrapper<Tenant>().eq(Tenant::getId, dto.getId());
        } else if (StringUtils.isNotEmpty(dto.getTenantId())) {
            query = new LambdaQueryWrapper<Tenant>().eq(Tenant::getTenantId, dto.getTenantId());
        } else {
            throw new RuntimeException("租户ID不能为空");
        }
        tenantMapper.delete(query);
    }

    @Override
    public void updateTenant(TenantUpdateDTO dto) {
        Tenant tenant = CONVERT.tenantUpdateDTO2Tenant(dto);
        tenantMapper.updateById(tenant);
    }


}